In [8]:
# This Python script is designed to show you how to export data to a file.
# First a very simple example.
import numpy as np 
In [9]:
# We generate an x array with elements 1 to 10 in steps of 2.  
# We also calculate y2 and y3 values as x^2 and x^3, respectively.
x = np.arange(1, 10, 2)
y2 = x**2
y3 = x**3
x, y2, y3
Out[9]:
(array([1, 3, 5, 7, 9]),
 array([ 1,  9, 25, 49, 81], dtype=int32),
 array([  1,  27, 125, 343, 729], dtype=int32))
In [10]:
# Ultimately, I intend to export a matrix of data to my file.  The matrix
# is constructed as follows:
M1= np.matrix([x, y2, y3])
M1
Out[10]:
matrix([[  1,   3,   5,   7,   9],
        [  1,   9,  25,  49,  81],
        [  1,  27, 125, 343, 729]])
In [11]:
# The matrix above has x as the first row, y2 as the second row, and y3 as
# the third row.  I'd rather have x as the first column, y2 as the second
# column, and y3 as the third column.  This is achieved by transposing the
# matrix above.
M2 = np.transpose(M1)
M2
Out[11]:
matrix([[  1,   1,   1],
        [  3,   9,  27],
        [  5,  25, 125],
        [  7,  49, 343],
        [  9,  81, 729]])
In [12]:
# We will use 'np.savetxt()' to write the data to a file.  This line will write the
# data to a file in the same directory as the Jupyter Notebook script (.ipynb file).
# The file does not need to exist in order to execute this command.
# If the file doesn't exist, it will be created.  If the file does exist
# already, it will be overwritten.
np.savetxt('Jupyter matrix data.txt', M2) 
In [13]:
# Suppose that you now wanted to appenda row of data to the 'matrix data' file
# that we just created.   You can do this by openning the file in append mode
# i.e. using the 'a' option in 'open()' and the using 'np.savetxt()' again.  
# Note that the 'with' statement closes the file after indented lines of code
# have executed.
newRow = [[11, 11**2, 11**3]]
with open('Jupyter matrix data.txt', 'a') as f:
    np.savetxt(f, newRow)
In [14]:
# Let's import the data file to verify that it has been written properly.
Data = np.loadtxt('Jupyter matrix data.txt')
Data
Out[14]:
array([[1.000e+00, 1.000e+00, 1.000e+00],
       [3.000e+00, 9.000e+00, 2.700e+01],
       [5.000e+00, 2.500e+01, 1.250e+02],
       [7.000e+00, 4.900e+01, 3.430e+02],
       [9.000e+00, 8.100e+01, 7.290e+02],
       [1.100e+01, 1.210e+02, 1.331e+03]])